﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XiaoYuStock.Model;
using XiaoYuStock.Model.Models;
using System.Data;
using System.Data.Entity;
using XiaoYuStock.Model.Request;
using XiaoYuStock.Model.Entities;

namespace XiaoYuStockAnalysis.BusinessLogic.Business
{
    public class HistoryDataBusiness
    {

        public bool SynDataExtend(HistoryData model)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            ShareContext dbContext = new ShareContext();
            var query = from m in dbContext.HistoryData
                        where m.ShareCode == model.ShareCode && m.CurrentDate == model.CurrentDate
                        select m;
            if (query.Any())
            {
                var m = query.FirstOrDefault();

                m.YesterdayCost = model.YesterdayCost;
                m.Support = model.Support;
                m.Pressure = model.Pressure;
                m.WeekTradeRate = model.WeekTradeRate;
                m.WeekDiffPrice = model.WeekDiffPrice;
                m.MonthTradeRate = model.MonthTradeRate;
                m.MonthDiffPrice = model.MonthDiffPrice;
                m.YearTradeRate = model.YearTradeRate;
                m.YearDiffPrice = model.YearDiffPrice;
                m.Ltg = model.Ltg;
                m.Mgjzc = model.Mgjzc;
                m.Income = model.Income;

                dbContext.Entry(m).State = EntityState.Modified;

                return dbContext.SaveChanges() > 0;
            }
            return false;
        }

        public bool SynData(HistoryData model)
        {
            if (model == null)
                throw new ArgumentNullException("model");
            if (model.CurrentDate == null)
                throw new ArgumentNullException("CurrentDate");

            ShareContext dbContext = new ShareContext();
            var query = from m in dbContext.HistoryData
                        where m.ShareCode == model.ShareCode && m.CurrentDate == model.CurrentDate
                        select m;
            if (query.Any())
            {
                var m = query.FirstOrDefault();
                m.MaxAmount = model.MaxAmount;
                m.MinAmount = model.MinAmount;
                m.OpenAmount = model.OpenAmount;
                m.TradeAmount = model.TradeAmount;
                m.TradeCount = model.TradeCount;
                m.CloseAmout = model.CloseAmout;
                m.YesterdayCloseAmount = model.YesterdayCloseAmount;

                m.YesterdayCost = model.YesterdayCost;
                m.Support = model.Support;
                m.Pressure = model.Pressure;
                m.WeekTradeRate = model.WeekTradeRate;
                m.WeekDiffPrice = model.WeekDiffPrice;
                m.MonthTradeRate = model.MonthTradeRate;
                m.MonthDiffPrice = model.MonthDiffPrice;
                m.YearTradeRate = model.YearTradeRate;
                m.YearDiffPrice = model.YearDiffPrice;
                m.Ltg = model.Ltg;
                m.Mgjzc = model.Mgjzc;
                m.Income = model.Income;
                dbContext.Entry(m).State = EntityState.Modified;

            }
            else
            {
                model.CreateDate = DateTime.Now;
                dbContext.Entry(model).State = EntityState.Added;
            }
            return dbContext.SaveChanges() > 0;
        }


        public IEnumerable<HistoryData> GetDataList(HistoryRequest request = null)
        {
            request = request ?? new HistoryRequest();

            using (var dbContext = new ShareContext())
            {
                IQueryable<HistoryData> query = dbContext.HistoryData;
                if (!string.IsNullOrWhiteSpace(request.ShareCode))
                {
                    query = query.Where(m => m.ShareCode == request.ShareCode);
                }
                if (!string.IsNullOrWhiteSpace(request.CustomerCode))
                {
                    query = query.Where(m => m.ShareCode == request.CustomerCode);
                }
                if (request.CurrentDate.HasValue)
                {
                    var begin = request.CurrentDate.Value.Date;
                    query = query.Where(m => m.TradeTime == begin);

                }

                if (request.MinRate.HasValue)
                {
                    query = query.Where(m => m.TradeRate >= request.MinRate.Value || !m.TradeRate.HasValue);
                }
                if (request.MaxRate.HasValue)
                {
                    query = query.Where(m => m.TradeRate <= request.MaxRate.Value || !m.TradeRate.HasValue);
                }
                return query.OrderByDescending(u => u.TradeTime).ToPagedList(request.PageIndex, request.PageSize);
            }
        }

        public IEnumerable<HistoryDataModel> GetList(HistoryRequest request = null)
        {
            request = request ?? new HistoryRequest();

            using (var dbContext = new ShareContext())
            {
                var query = from my in dbContext.HistoryData
                            join s in dbContext.ShareList on my.ShareCode equals s.ShareCode
                            where s.Status == (int)ShareState.Active
                            select new { my, ShareName = s.ShareName };
                if (!string.IsNullOrWhiteSpace(request.ShareCode))
                {
                    query = query.Where(m => m.my.ShareCode == request.ShareCode);
                }
                if (!string.IsNullOrWhiteSpace(request.CustomerCode))
                {
                    query = query.Where(m => m.my.ShareCode == request.CustomerCode);
                }
                if (request.CurrentDate.HasValue)
                {
                    var begin = request.CurrentDate.Value.Date;
                    query = query.Where(m => m.my.TradeTime == begin);

                }
                if (request.MinRate.HasValue)
                {
                    query = query.Where(m => m.my.TradeRate >= request.MinRate.Value || !m.my.TradeRate.HasValue);
                }
                if (request.MaxRate.HasValue)
                {
                    query = query.Where(m => m.my.TradeRate <= request.MaxRate.Value || !m.my.TradeRate.HasValue);
                }
                var totalItemCount = query.Count();
                if (request.PageIndex < 1)
                    request.PageIndex = 1;
                var itemIndex = (request.PageIndex - 1) * request.PageSize;
                var pageOfQuery = query.OrderByDescending(m => m.my.TradeTime).Skip(itemIndex).Take(request.PageSize);
                if (request.OrderBy == (int)ShareOrder.Gain) //涨幅
                {
                    pageOfQuery = query.OrderByDescending(m => m.my.TradeRate).Skip(itemIndex).Take(request.PageSize);
                }
                else if (request.OrderBy == (int)ShareOrder.Decline) //跌幅
                {
                    pageOfQuery = query.OrderBy(m => m.my.TradeRate).Skip(itemIndex).Take(request.PageSize);
                }
                else if (request.OrderBy == (int)ShareOrder.HighPrice)
                {
                    pageOfQuery = query.OrderByDescending(m => m.my.OpenAmount).Skip(itemIndex).Take(request.PageSize);
                }
                else if (request.OrderBy == (int)ShareOrder.LowPrice)
                {
                    pageOfQuery = query.OrderBy(m => m.my.OpenAmount).Skip(itemIndex).Take(request.PageSize);
                }
                var pageOfItems = pageOfQuery.ToList().Select(t =>
                {
                    return new HistoryDataModel
                    {
                        Id = t.my.Id,
                        ShareCode = t.my.ShareCode,
                        ShareName = t.ShareName,
                        TradeAmount = t.my.TradeAmount,
                        TradeTime = t.my.TradeTime,
                        TradeCount = t.my.TradeCount,
                        CloseAmout = t.my.CloseAmout,
                        CurrentDate = t.my.CurrentDate,
                        MaxAmount = t.my.MaxAmount,
                        MinAmount = t.my.MinAmount,
                        OpenAmount = t.my.OpenAmount,
                        WeekDay = t.my.WeekDay,
                        TradeRate = t.my.TradeRate,
                        DiffPrice = t.my.DiffPrice,
                        Income = t.my.Income,
                        Ltg = t.my.Ltg ?? 0,
                        Mgjzc = t.my.Mgjzc,
                        YesterdayCloseAmount = t.my.YesterdayCloseAmount
                    };
                });

                return new PagedList<HistoryDataModel>(pageOfItems, request.PageIndex, request.PageSize, totalItemCount);
            }


        }

        public List<HistoryData> GetSyncList(int id, string code)
        {
            var dbContext = new ShareContext();
            if (id > 0)
            {
                if (string.IsNullOrWhiteSpace(code))
                    return null;
                var current = dbContext.HistoryData.FirstOrDefault(t => t.Id == id && t.ShareCode == code);
                if (current == null)
                    return null;
            }
            var query = from my in dbContext.HistoryData
                        where my.Id > id
                        select my;

            return query.Take(100).ToList();
        }


        public HistoryData GetMaxModel()
        {
            var dbContext = new ShareContext();
            var current = dbContext.HistoryData.OrderByDescending(x => x.Id).FirstOrDefault();
            return current;

        }
        public HistoryData GetModel(HistoryRequest request = null)
        {
            HistoryData result = new HistoryData();
            request = request ?? new HistoryRequest();

            var dbContext = new ShareContext();

            var query = from my in dbContext.HistoryData
                        select my;
            if (!string.IsNullOrWhiteSpace(request.ShareCode))
            {
                query = query.Where(m => m.ShareCode == request.ShareCode);
            }
            if (!string.IsNullOrWhiteSpace(request.CustomerCode))
            {
                query = query.Where(m => m.ShareCode == request.CustomerCode);
            }
            if (request.CurrentDate.HasValue)
            {
                var begin = request.CurrentDate.Value.Date;
                query = query.Where(m => m.TradeTime == begin);

            }

            result = query.FirstOrDefault();
            return result;
        }


    }
}
